import { asyncRoutes, constantRoutes } from '@/router'
import util from '@/utils/common'
import router from '@/router'
import defaultSettings from '@/settings'

const { topbarVisible,mutiSidebarVisible } = defaultSettings
/**
 *
 * @param  {Array} menus 后台返回的用户权限json
 * @param  {Array} allRouter  前端配置好的所有动态路由的集合
 * @return {Array} realRoutes 过滤后的路由
 */

export function recursionRouter(menus = [], allRouter = []) {
    var realRoutes = []
    menus.forEach((item) => {
        allRouter.forEach((v) => {
            if (item.moduleCode === v.meta.code) {
                if (item.childModules && item.childModules.length > 0) {
                    v.children = recursionRouter(item.childModules, v.children)
                }
                v.meta.title = item.moduleName ||  v.meta.title 
                v.meta.moduleId = item.moduleId
                v.meta.icon = item.moduleIcon?item.moduleIcon:v.meta.icon
                realRoutes.push(v)
            }
        })
    })
    return realRoutes
}

const state = {
  routes: [],
  addRoutes: [],
  sidebarMenu:[],
  realMenus:[],
  currentPath:'',
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    
  },
  SET_PATH:(state, path) => {
    state.currentPath = path
    if(topbarVisible || mutiSidebarVisible){
    	const currentRootpath = `/${state.currentPath.split("/")[1]}`
    	state.realMenus = []
    	state.routes.forEach((v) => {
	        if(v.path === currentRootpath && v.children){
	        	state.realMenus = v.children || []
	        }
	    })
    }else{
    	state.realMenus = state.routes
    }
  }
}

const actions = {
	generateRoutes({commit}, menus) {
		return new Promise(resolve => {
			/*  根据后台权限跟我们定义好的权限对比，筛选出对应的路由并加入到router*/
			let allAsyncRoutes = util.deepCopy(asyncRoutes) 
			const accessedRoutes = recursionRouter(menus, allAsyncRoutes)
			/*  动态添加路由 */
			router.addRoutes(accessedRoutes)
			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	},
	setPath({commit}, path) {
		return new Promise(resolve => {
			commit('SET_PATH', path)
			resolve()
		})
	}
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
